package com.liuchuanzheng.lcz_wanandroid.module.user.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.liuchuanzheng.lcz_wanandroid.R
import com.liuchuanzheng.lcz_wanandroid.base.BaseVMActivity
import com.liuchuanzheng.lcz_wanandroid.databinding.ActivityLoginBinding
import com.liuchuanzheng.lcz_wanandroid.ext.showToast
import com.liuchuanzheng.lcz_wanandroid.module.user.viewmodel.LoginViewModel

/**
 * @author 刘传政
 * @date 2021/9/17 0017 10:06
 * QQ:1052374416
 * 电话:18501231486
 * 作用:
 * 注意事项:
 */
class LoginActivity : BaseVMActivity<LoginViewModel>() {
    lateinit var mViewBinding: ActivityLoginBinding

    companion object {
        fun start(context: Context) {
            Intent(context, LoginActivity::class.java).run {
                context.startActivity(this)
            }
        }
    }

    /**
     * 因为系统自带的设置view方法有很多种,id,view都可以.所以这里不像
     * 大家都用id的封装方式,那是限制了自己
     * 建议用viewBinding的方式。个人不喜欢dataBinding
     */
    override fun setContentView() {
        mViewBinding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(mViewBinding.root)
    }

    /**
     * 进行观察订阅
     */
    override fun observeViewModel() {
        mViewModel.run {
            liveData_loginResult.observe(this@LoginActivity,{
                if (it) {
                    finish()
                }

            })
            liveData_loading.observe(this@LoginActivity,{
                if (it) {
                    showLoading(getString(R.string.logging_in))
                }else{
                    hideLoading()
                }

            })
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewBinding.ivClose.setOnClickListener { finish() }
        mViewBinding.btnLogin.setOnClickListener {
            mViewBinding.tilAccount.error = ""
            mViewBinding.tilPassword.error = ""
            val account = mViewBinding.tietAccount.text.toString()
            val password = mViewBinding.tietPassword.text.toString()
            when {
                account.isEmpty() -> mViewBinding.tilAccount.error = getString(R.string.account_can_not_be_empty)
                password.isEmpty() -> mViewBinding.tilPassword.error = getString(R.string.password_can_not_be_empty)
                else ->{
                    mViewModel.login(account, password)
                }
            }
        }
        mViewBinding.tvGoRegister.setOnClickListener {
            showToast(R.string.coming_soon)
        }
    }
}